package com.community.backend.service.impl;

import com.community.backend.mapper.FeeMapper;
import com.community.backend.mapper.PropertyMapper;
import com.community.backend.mapper.ShareFeeMapper;
import com.community.backend.mapper.UserMapper;
import com.community.backend.pojo.vo.ReportVO;
import com.community.backend.service.ReportService;
import com.community.backend.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Resource
    private FeeMapper feeMapper;
    @Resource
    private PropertyMapper propertyMapper;
    @Resource
    private ShareFeeMapper shareFeeMapper;
    @Resource
    private UserMapper userMapper;


    @Override
    public ReportVO turnoverStatistics(LocalDate begin, LocalDate end,String status) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 2. 生成日期列表（用临时变量循环，避免修改入参begin）
        List<LocalDate> localDateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            localDateList.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
        log.info("统计日期范围：{} - {}，共{}天", begin, end, localDateList.size());

        // 3. 同步统计：每日已缴金额、每日未缴金额
        List<BigDecimal> paidList = new ArrayList<>();   // 已缴金额列表
        List<BigDecimal> unpaidList = new ArrayList<>(); // 未缴金额列表
        for (LocalDate date : localDateList) {
            LocalDateTime dayBegin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime dayEnd = LocalDateTime.of(date, LocalTime.MAX);

            // 统计当天已缴金额（调用工具方法，避免重复代码）
            BigDecimal dailyPaid = calculateDailyAmount(dayBegin, dayEnd, "已缴");
            // 统计当天未缴金额
            BigDecimal dailyUnpaid = calculateDailyAmount(dayBegin, dayEnd, "未缴");

            // 加入列表（与日期列表一一对应）
            paidList.add(dailyPaid);
            unpaidList.add(dailyUnpaid);

            log.debug("日期[{}] - 已缴：{} 元，未缴：{} 元", date, dailyPaid, dailyUnpaid);
        }
        // 4. 日期转字符串（适配前台，避免LocalDate序列化问题）
        List<String> dateStrList = localDateList.stream()
                .map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                .toList();


        ReportVO reportVO = new ReportVO(dateStrList, paidList, unpaidList);
        log.info("营业额统计完成"+reportVO);
        return reportVO;
    }
    private BigDecimal calculateDailyAmount(LocalDateTime begin, LocalDateTime end, String status) {
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        // 水费求和（空值处理）
        BigDecimal feeSum = feeMapper.paidSumByMap(map);
        feeSum = feeSum == null ? BigDecimal.ZERO : feeSum;

        // 公摊费求和（空值处理）
        BigDecimal propertySum = propertyMapper.paidSumByMap(map);
        propertySum = propertySum == null ? BigDecimal.ZERO : propertySum;

        // 物业费求和（空值处理）
        BigDecimal shareSum = shareFeeMapper.paidSumByMap(map);
        shareSum = shareSum == null ? BigDecimal.ZERO : shareSum;

        // 三者总和
        BigDecimal total = feeSum.add(propertySum).add(shareSum);
        log.trace("费用汇总：水费{} + 公摊费{} + 物业费{} = 总计{}", feeSum, propertySum, shareSum, total);
        return total;
    }








        @Override
    public ReportVO contrast(LocalDate begin, LocalDate end) {

        return null;
    }

    @Override
    public List<Integer> statisticsUsers() {
        List<Integer> list = new ArrayList<>(); // 使用ArrayList实现类
        // 获取以 login:USER:为前缀的数据，并计算数量
        Set<String> keys = RedisUtils.redis().keys("login:USER:*");
        int online = keys != null ? keys.size() : 0;
        System.out.println("在线用户数量" + online);
        list.add(online);
        Integer all = userMapper.selectAll();
        System.out.println("用户数量" + all);
        list.add(all);
        System.out.println("用户统计list:"+list);
        return list;
    }

    @Override
    public Map<String, Integer> statisticsFees() {
//        List<Integer> list = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
//        Map map = new HashMap();
//        map.put("project","水费，电费，煤气费");
//        map.put("status","已缴，未缴");
        String[] statuses = {"已缴", "未缴"};
        String[] projects = {"水费", "电费", "煤气费","停车费"};
        for (String status : statuses) {
            Integer share = shareFeeMapper.selectAllByStatus(status);
            System.out.println("qqq"+share);
            Integer property = propertyMapper.selectAllByStatus(status);
            System.out.println("qqq"+property);
            for (String project : projects){
                Integer fee = feeMapper.selectAllByStatusAndProject(status,project);
                map.put(project+status,fee);
//                list.add(fee);
                System.out.println("费用统计fee:"+fee);
            }
            map.put("公摊费"+status,share);
            map.put("物业费"+status,property);
//            list.add(share);
//            list.add(property);
            System.out.println("费用统计share:"+share);
            System.out.println("费用统计property:"+property);
        }
        System.out.println("费用统计map:"+map);
        return map;
    }


}
